using System.Windows;
using System.Windows.Controls;
using Microsoft.Extensions.DependencyInjection;
using Microsoft.Extensions.Logging;
using DocumentCreationSystem.Services;
using DocumentCreationSystem.Models;

namespace DocumentCreationSystem.Views
{
    /// <summary>
    /// 项目错误修复对话框
    /// </summary>
    public partial class ProjectErrorDialog : Window
    {
        private readonly ILogger<ProjectErrorDialog> _logger;
        private readonly IServiceProvider _serviceProvider;
        // ProjectFixUtility已移除

        public Project? CurrentProject { get; set; }
        public Project? FixedProject { get; private set; }
        public bool IsFixed { get; private set; }

        public ProjectErrorDialog(IServiceProvider serviceProvider, Project? currentProject = null, string? errorMessage = null)
        {
            InitializeComponent();
            
            _serviceProvider = serviceProvider;
            _logger = serviceProvider.GetRequiredService<ILogger<ProjectErrorDialog>>();
            // ProjectFixUtility已移除
            
            CurrentProject = currentProject;
            
            InitializeDialog(errorMessage);
        }

        private void InitializeDialog(string? errorMessage = null)
        {
            // 设置错误信息
            if (!string.IsNullOrEmpty(errorMessage))
            {
                ErrorMessageTextBlock.Text = errorMessage;
            }

            // 设置默认值
            if (CurrentProject != null)
            {
                NovelTitleTextBox.Text = CurrentProject.Name;
                ProjectNameTextBox.Text = CurrentProject.Name;
                ProjectPathTextBox.Text = CurrentProject.RootPath;
            }

            // 绑定单选按钮事件
            CreateNovelProjectRadio.Checked += (s, e) => 
            {
                NovelProjectPanel.IsEnabled = true;
                NewProjectPanel.IsEnabled = false;
            };

            CreateNewProjectRadio.Checked += (s, e) => 
            {
                NovelProjectPanel.IsEnabled = false;
                NewProjectPanel.IsEnabled = true;
            };

            CancelOperationRadio.Checked += (s, e) => 
            {
                NovelProjectPanel.IsEnabled = false;
                NewProjectPanel.IsEnabled = false;
            };
        }

        private async void Fix_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                FixButton.IsEnabled = false;
                FixButton.Content = "修复中...";

                if (CancelOperationRadio.IsChecked == true)
                {
                    DialogResult = false;
                    Close();
                    return;
                }

                if (CreateNovelProjectRadio.IsChecked == true)
                {
                    // 为当前项目创建小说项目记录
                    await FixCurrentProjectAsync();
                }
                else if (CreateNewProjectRadio.IsChecked == true)
                {
                    // 创建新的正式项目
                    await CreateNewFormalProjectAsync();
                }

                if (IsFixed)
                {
                    MessageBox.Show("项目修复成功！现在可以正常使用写书功能了。", "修复成功", 
                        MessageBoxButton.OK, MessageBoxImage.Information);
                    DialogResult = true;
                    Close();
                }
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修复项目时发生错误");
                MessageBox.Show($"修复失败：{ex.Message}", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
            finally
            {
                FixButton.IsEnabled = true;
                FixButton.Content = "修复";
            }
        }

        private async Task FixCurrentProjectAsync()
        {
            if (CurrentProject == null)
            {
                MessageBox.Show("当前项目信息无效", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var novelTitle = NovelTitleTextBox.Text.Trim();
            var creativeDirection = CreativeDirectionTextBox.Text.Trim();

            if (string.IsNullOrEmpty(novelTitle))
            {
                MessageBox.Show("请输入小说标题", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            _logger.LogInformation($"为项目ID {CurrentProject.Id} 创建小说项目记录");

            var success = false; // ProjectFixUtility已移除
            if (success)
            {
                IsFixed = true;
                FixedProject = CurrentProject;
                _logger.LogInformation("小说项目记录创建成功");
            }
            else
            {
                MessageBox.Show("创建小说项目记录失败，请查看日志了解详情", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private async Task CreateNewFormalProjectAsync()
        {
            if (CurrentProject == null)
            {
                MessageBox.Show("当前项目信息无效", "错误", MessageBoxButton.OK, MessageBoxImage.Error);
                return;
            }

            var projectName = ProjectNameTextBox.Text.Trim();
            var novelTitle = NovelTitleTextBox.Text.Trim();
            var creativeDirection = CreativeDirectionTextBox.Text.Trim();

            if (string.IsNullOrEmpty(projectName) || string.IsNullOrEmpty(novelTitle))
            {
                MessageBox.Show("请填写完整的项目信息", "提示", MessageBoxButton.OK, MessageBoxImage.Warning);
                return;
            }

            _logger.LogInformation($"创建新的正式项目: {projectName}");

            Project? newProject = null; // ProjectFixUtility已移除

            if (newProject != null)
            {
                IsFixed = true;
                FixedProject = newProject;
                _logger.LogInformation($"新项目创建成功，ID: {newProject.Id}");
            }
            else
            {
                MessageBox.Show("创建新项目失败，请查看日志了解详情", "错误", 
                    MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void Cancel_Click(object sender, RoutedEventArgs e)
        {
            DialogResult = false;
            Close();
        }
    }
}
